local changhe = fk.CreateSkill{
  name = "xiaobai__changhe",
}

local XBB = require "packages.xiaobai.util"

Fk:loadTranslationTable{
  ["xiaobai__changhe"] = "长河",
  [":xiaobai__changhe"] = "游戏开始时，将未出场的“小白杯”武将正面向上洗入牌堆，这些牌均视为♠9的锦囊牌，"..
    "这些牌进入弃牌堆后销毁，效果为：此牌可当作此武将技能描述中的一张基本牌或普通锦囊牌使用。",
  ["@xiaobai__tianxiadaba"] = "",
  ["#xiaobai__changhe"] = "%from 将 %arg 张牌洗入牌堆。",
  ["xiaobai__tianxiadaba_card"] = "白",
  ["@&xiaobai__changhe"] = "长河"
}

-- 获取加入游戏的卡的牌名（暂不考虑装备牌），常用于泛转化技能的interaction
---@param fk Engine @ Fk
---@param true_name? boolean @ 是否使用真实卡名（即不区分【杀】、【无懈可击】等的具体种类）
---@return string[] @ 返回牌名列表
local function getAllCardNames(fk, true_name)
  local all_names = {}
  for _, card in ipairs(fk.cards) do
    if card.type == Card.TypeBasic then
      table.insertIfNeed(all_names, true_name and card.trueName or card.name)
    elseif card.type == Card.TypeTrick and card.sub_type ~= Card.SubtypeDelayedTrick then
      table.insertIfNeed(all_names, true_name and card.trueName or card.name)
    end
  end
  return all_names
end

changhe:addEffect(fk.GameStart, {
  anim_type = "control",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(changhe.name)
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local card_names = getAllCardNames(Fk, true)
    local packages = table.map(table.filter(Fk.package_names, function (pname)
      return pname:startsWith("xiaobai")
    end), function (name)
      return Fk.packages[name]
    end)
    local room_generals = table.map(room.players, function (p)
      return p.general ~= "hiddenone" and p.general or p:getMark("__hidden_general")
    end)
    if room:getSettings("enableDeputy") then
      table.insertTableIfNeed(room_generals, table.map(room.players, function (p)
        return p.deputyGeneral ~= "hiddenone" and p.deputyGeneral or p:getMark("__hidden_deputy")
      end))
    end
    --- 使用模式匹配找到所有【】之间的内容
    local function extract_bracket_contents(str)
      local result = {}
      for content in str:gmatch("【(.-)】") do
          table.insert(result, content)
      end
      return result
    end
    local cards = {}
    for _, pack in ipairs(packages) do
      for _, g in ipairs(pack.generals) do
        if (not g.hidden and not g.total_hidden and not table.contains(room_generals, g.name)) then
          local card = room:printCard(g.name.."_card", Card.Spade, 9)
          room:setCardMark(card, "@xiaobai__tianxiadaba", Fk:translate(g.name))
          local all_card_names = {}
          for _, sn in ipairs(g.other_skills) do
            local skill_translation = Fk:translate(":"..sn, "zh_CN")
            local skill_card_names = extract_bracket_contents(skill_translation)
            local card_name_in_skill = table.filter(card_names, function (cn)
              return table.contains(skill_card_names, Fk:translate(cn, "zh_CN"))
            end)
            table.insertTableIfNeed(all_card_names, card_name_in_skill)
          end
          room:addTableMark(player, "@&xiaobai__changhe", g.name)
          room:findGeneral(g.name)
          room:setCardMark(card, "xiaobai__tianxiadaba_card", all_card_names)
          table.insert(cards, card)
        end
      end
    end
    room:changeCardArea(cards, Card.DrawPile)
    room:sendLog{
      type = "#xiaobai__changhe",
      from = player.id,
      arg = #cards
    }
    for _, p in ipairs(room.alive_players) do
      room:handleAddLoseSkills(p, "xiaobai__dabai&", nil, false, true)
    end
  end,
})

changhe:addEffect(fk.AfterCardsMove, {
  mute = true,
  is_delay_effect = true,
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(changhe.name)
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local removeCards = {} ---@type integer[]
    for _, move in ipairs(data) do
      if move.toArea == Card.DiscardPile then
        for _, info in ipairs(move.moveInfo) do
          table.insertIfNeed(removeCards, info.cardId)
        end
      end
    end
    removeCards = room.logic:moveCardsHoldingAreaCheck(removeCards)
    removeCards = table.filter(removeCards, function (id)
      return XBB.startsWithEndsWith(Fk:getCardById(id).name)
    end)
    if #removeCards > 0 then
      player:broadcastSkillInvoke(changhe.name)
      room:notifySkillInvoked(player, changhe.name, "negative")
      for _, cid in ipairs(removeCards) do
        room:removeTableMark(player, "@&xiaobai__changhe", string.gsub(Fk:getCardById(cid).name, "_card$", ""))
      end
      room:moveCardTo(removeCards, Card.Void, nil, fk.ReasonJustMove, changhe.name, nil, true, player, "xiaobai__changhe_remove")
    end
  end
})

return changhe